from flask import Blueprint, render_template, request, jsonify, session
from select import select
from flask import redirect, url_for
import hashlib

from utils.database_util import query_date
from utils.util import ArticleUtil
article_read = Blueprint('article_read', __name__)


@article_read.route('/article_read' ,methods=['GET', 'POST'])
def index():
    return render_template("article_read.html")

@article_read.route('/article/list' , methods=['GET', 'POST'])
def article_list():
    sql_str = "select article.*, users.nickname from article left join users on users.userid = article.userid order by article.updatetime desc limit 10"
    result = query_date(sql_str)
    result = ArticleUtil.transform_articles(result)
    if len(result):
        return jsonify({'code':1, 'info':result})
    else:
        return jsonify({'code':0, 'info':[]})

@article_read.route('/article/list/<int:page>', methods=['GET','POST'])
def article_list_limit(page):

    sql = 'select count(articleid) as `article_number` from article'
    select_sql = 'select article.*, users.nickname from article left join users on users.userid = article.userid order by updatetime desc limit {},{}'
    keyword = request.form.get('keyword')
    if keyword is not None:
        sql = 'select count(articleid) as `article_number` from article where headline like "%'+keyword+'%"'
        select_sql = 'select article.*, users.nickname from article left join users on users.userid = article.userid where headline like "%'+keyword+'%" order by updatetime desc limit {},{}'
        keyword = request.form.get('keyword')
        print(keyword)
    number = 10
    result = query_date(sql)
    count = result[0]['article_number']
    max_page = int(count / number) + 1
    start = (page - 1) * number
    end = start + number
    sql_str = select_sql.format(start, 10)
    result = query_date(sql_str)
    result = ArticleUtil.transform_articles(result)
    if len(result):
        return jsonify({'code': 1, 'info': result, 'page': {'max_page': max_page, 'now_page': page}})
    else:
        return jsonify({'code': 0, 'info': []})

@article_read.route('/article/<int:article_id>',methods=['GET', 'POST'])
def article_info2(article_id):
    sql = 'select article.*, users.nickname from article left join users on users.userid = article.userid where articleid = %d' %article_id
    result = query_date(sql)
    result = ArticleUtil.transform_articles(result)
    if len(result) == 0:
        return render_template("error-404.html")
    else:
        read_sql = 'update article set readcount = {} where articleid={}'.format(result[0]['readcount']+1, article_id)
        query_date(read_sql)
        userid = session.get('userid')
        if userid is None:
            return redirect(url_for('user_center.login'))
        credit(userid, article_id)
        return render_template("article_read.html", article=result[0])



def credit(user_id, article_id):
    sql = 'select * from article where articleid=%d' % article_id
    articles = query_date(sql)
    article = articles[0] if len(articles) == 1 else None
    if user_id != article['userid']:
        article_credit = select_article_credit(article_id)
        user_credit = select_user_credit(user_id)
        if user_credit > article_credit:
            if is_buy(user_id, article_id):
                return True
            update_user_credit(user_id, (user_credit - article_credit), -article_credit,"阅读文章扣除积分",article_id)
            author_id = article['userid']
            author_credit = select_user_credit(author_id)
            update_user_credit(author_id,(author_credit + article_credit), article_credit,"文章被阅读获得积分",article_id)
            return True
        else:
            return False
    else:
        return True


def select_user_credit(user_id):
    sql = 'select * from users where userid=%d' % user_id
    user_info = query_date(sql)
    return user_info[0]["credit"]

def select_article_credit(article_id):
    sql = 'select * from article where articleid=%d' % article_id
    articles = query_date(sql)
    return articles[0]["credit"]

def update_user_credit(user_id, credit, number, type, article_id):
    sql = 'update users set credit = {} where userid={}'.format(credit, user_id)
    query_date(sql)
    sql2 = "INSERT INTO `credit` (`userid`, `category`, `target`, `credit`) VALUES (%s, %s, '%s', %s)" % (user_id, type, article_id, number)
    query_date(sql2)
    print(user_id, " : " , credit)

def is_buy(user_id, article_id):
    sql = 'select * from credit where userid=%d and target=%d' % (user_id, article_id)
    result = query_date(sql)
    return len(result) > 0

